<!doctype html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security" xmlns:auth="">
<auth:data uri="/data/yd/tag/list.json,/data/yd/icon/add"/>

<head>
    <th:block th:include="common/head::noXadmin('添加图标')"/>
    <style>
        .layui-upload-list {
            overflow-y: scroll;
            height: 300px;
            padding: 0px;
        }

        .layui-upload-list li {
            float: left;
            border: 1px solid #e6e6e6;
            margin: 0px 10px 10px 10px;
            background-color: white;
            cursor: pointer;
            height: 78px;
            position: relative;
            width: 78px;
        }

        .layui-upload-list li svg {
            padding: 20px;
        }

        .layui-upload-list li .redo,
        .layui-upload-list li .del {
            width: 80px;
            position: absolute;
            height: 24px;
            background-color: #0c0c0ca6;
            text-align: center;
            color: white;
            display: none;
            bottom: -1px;
            left: -1px;
        }

        .layui-upload-list .layui-progress {
            position: absolute;
            width: 80px;
            bottom: 0px;
            display: none;
        }

        .layui-upload-list li.active,
        .layui-upload-list li:hover {
            border-color: #aaa;
        }

        .layui-upload-list li.active:hover .del {
            display: block;
        }

        .tags {
            height: 300px;
            overflow: scroll;
        }

        .tags button {
            margin: 10px;
        }

        .tags button.active {
            border-color: red;
        }
    </style>
</head>
<body class="layui-layout layui-layout-admin" style="background-color: rgb(250,250,251)">
<div class="layui-container">
    <div class="layui-row">
        <div class="layui-col-md12 text-align-center layui-bg-gray " id="selectIcon"
             style="height: 100px;vertical-align: middle;line-height: 100px">
            <i class="layui-icon layui-icon-upload " style="color: red"></i>
            将图标 SVG 文件拖拽至框内上传<a class="" href="javascript:;"> 选择文件</a>
        </div>
    </div>
    <div class="layui-row layui-col-space30 " style="margin: 40px 30px 0px 30px ">
        <div class="layui-col-md6 layui-bg-gray">
            <ul class="layui-upload-list" id="demoList">

            </ul>
        </div>
        <div class="layui-col-md6">
            <div class="layui-form-item">
                <label class="layui-form-label">名称</label>
                <div class="layui-input-block">
                    <input type="text" id="name" name="name" autocomplete="off" placeholder="图标名称"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">标签</label>
                <div class="layui-input-block">
                    <input type="text" id="tags" name="tags" autocomplete="off" placeholder="图标标签"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-block tags">
                </div>
            </div>
        </div>
    </div>
    <div class="layui-row text-align-center layui-bg-gray " style="height: 60px;line-height: 60px;">
        <div class="layui-form-item">
            <button type="button" class="layui-btn" id="selectIconAction">开始上传</button>
        </div>
    </div>
</div>
<script>

</script>
<script>
    layui.use(['form', 'upload', 'laytpl'], function () {
        var form = layui.form
            , upload = layui.upload
            , $ = layui.jquery
        ;
        const IconTag = function (options) {
            let that = this;
            this.options = {
                box: $(".tags"),
                tags: [{tagId: 0, tagName: "tag0"}, {tagId: 1, tagName: 'tag1'}],
                actClass: 'active'
            };
            options = options || {};
            for (let o in options) {
                this.options[o] = options[o];
            }

            function init() {
                options = that.options;
                let box = options.box;
                options.tags.forEach((tag) => {
                    let btn = $(['<button type="button" class="layui-btn layui-btn-primary" d="', tag.tagId, '">', tag.tagName, '</button>'].join(''));
                    btn.on('click', function () {
                        if (!that.file) {
                            layer.msg('non bind file');
                            return;
                        }
                        console.log(options.actClass);
                        btn.toggleClass(options.actClass);
                        let tags = [];
                        box.find("." + options.actClass).each((n, x) => tags.push({
                            tagId: x.getAttribute('d'),
                            tagName: x.innerText
                        }));

                        that.file.tags = tags;
                        if (typeof that.onchange === 'function') {
                            that.onchange(tags);
                        }
                    });
                    box.append(btn)
                });
            }

            $.ajax({
                url: rootPath + 'data/yd/tag/list.json',
                type: "GET",
                data: {
                    pageNum: 1,
                    pageSize: 100
                },
                dataType: "json",
                success: function (data) {
                    that.options.tags = data.data.list;
                    init();
                }
            });
            return {
                bindFile: function (file, onchange) {
                    that.file = file;
                    that.onchange = onchange || ((tags) => console.log(tags));
                    let fileTags = file.tags;
                    let box = that.options.box;
                    let actClsName = that.options.actClass;
                    box.find("." + actClsName).removeClass(actClsName);
                    fileTags.forEach((tag) => {
                        box.find('[d="' + tag.tagId + '"]').addClass(actClsName);
                    });
                }
            }
        }
        const iconTag = IconTag();

        //多文件列表示例
        var demoListView = $('#demoList')
            , uploadListIns = upload.render({
            elem: '#selectIcon'
            , url: '/data/yd/icon/add' //改成您自己的上传接口
            , accept: 'file'
            , multiple: true
            , auto: false
            , drag: true
            , bindAction: '#selectIconAction'
            , data: {
                name: function (file) {
                    return file.simpleName;
                },
                tagIds: function (file) {
                    return file.tags.map(x => x.tagId).join(',');
                }
            }
            , choose: function (obj) {
                let files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                let c2 = 0;
                for (let f in files) {
                    files[f].simpleName = files[f].name.split('\.')[0];
                    files[f].tags = [];
                }
                //读取本地文件
                obj.preview(function (index, file, result) {
                    file.text().then(function (text) {
                        var lis = $([
                            '<li  id="upload-', index, '",>',
                            text,
                            '  <div class="layui-progress">',
                            '    <div class="layui-progress-bar layui-bg-red" lay-percent="100%"></div>',
                            '  </div>',
                            '  <div class="del">',
                            '    <i class="layui-icon layui-icon-delete" style="font-size: 20px"></i>',
                            '  </div>',
                            '  <div class="redo layui-hide">',
                            '    <i class="layui-icon layui-icon-upload" style="font-size: 20px"></i>',
                            '  </div>',
                            '</li>'].join(''))
                        //修改svg属性
                        lis.find("svg").attr("width", 40).attr("height", 40);
                        //单个重传
                        lis.find('.redo').on('click', function () {
                            obj.upload(index, file);
                        });
                        lis.on('click', function () {
                            activeFile(files, index);
                        })

                        function activeFile(files, index) {
                            $("#name").val(files[index].simpleName);
                            lis.siblings('.active').removeClass('active');
                            lis.addClass('active');
                            iconTag.bindFile(files[index], (tags) => {
                                $("#tags").val(tags.map((x) => x.tagName).join(','));
                            });
                        }

                        //删除
                        lis.find('.del').on('click', function () {
                            delete files[index]; //删除对应的文件
                            lis.remove();
                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        });
                        demoListView.append(lis);
                        c2++;
                        (1 == c2) && activeFile(files, index);
                    })
                });
            }
            , done: function (res, index, upload) {
                if (res.code === 0) { //上传成功
                    let lis = demoListView.find('li#upload-' + index);
                    lis.remove();
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            , error: function (index, upload) {

            }, allDone: function (obj) { //当文件全部被提交后，才触发
                layer.msg(
                    ['总共：', obj.total, '<br/>成功：', obj.successful, '<br/>失败：', obj.aborted].join('')
                );
            }
        });
        form.on('submit(ok)', function (data) {
            return true;
        })
    });
</script>

</body>

</html>